package com.linkstec.musiccloud.controller;

import java.io.InputStream;
import java.util.Collection;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.linkstec.musiccloud.pojo.Song;
import com.linkstec.musiccloud.pojo.User;
import com.linkstec.musiccloud.service.SongService;
import com.linkstec.musiccloud.service.SonglistService;
import com.linkstec.musiccloud.service.UserService;
import com.linkstec.musiccloud.vo.SongListVos;

import sun.security.util.Password;

@Controller
@RequestMapping("user")
public class UserController {
	private static String adminName = null;// 先定义

	private static String adminpwd = null;// 1

	private static final String path = "D:/LOL/";// 文件保存路径

	static {
		try {
			// 获取当前类的加载器
			ClassLoader classLoader = UserController.class.getClassLoader();
			// 通过当前累加载器方法获得 文件db.properties的一个输入流
			InputStream is = classLoader.getResourceAsStream("db.properties");
			// 创建一个Properties 对象
			Properties properties = new Properties();
			// 加载输入流
			properties.load(is);

			adminName = properties.getProperty("adminName");
			adminpwd = properties.getProperty("adminpwd");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Autowired
	private UserService userService;

	@Autowired
	private SonglistService songlistService;

	@Autowired
	private SongService songService;

	/**
	 * @Description:TODO 用户登录
	 * @author: shuaibizhe
	 * @date: 2018年11月22日 下午6:38:37
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public String login(User user, HttpServletRequest request) {
		JSONObject json = new JSONObject();
		if (user.getUserName().equals(adminName) && user.getPassword().equals(adminpwd)) {
			json.put("msg", 2);
		} else {
			User user2 = null;
			try {
				user2 = userService.login(user);
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (user2 != null) {
				json.put("msg", 1);
				json.put("role", user2.getSinger());
				request.getSession().setAttribute("loginUser", user2);
			} else {
				json.put("msg", "用户名或密码不正确");
			}
		}
		return json.toString();
	}

	/**
	 * @Description:TODO 跳转到index界面
	 * @author: shuaibizhe
	 * @date: 2018年11月22日 下午7:24:06
	 * @param role
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "toIndex")
	public ModelAndView toIndex(ModelAndView mv) {
		mv.setViewName("index");
		return mv;
	}

	/**
	 * @Description:TODO 注册
	 * @author: shuaibizhe
	 * @date: 2018年11月22日 下午8:41:37
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "register")
	public String register(User user, HttpServletRequest request) {
		try {
			userService.register(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.getSession().setAttribute("loginUser", user);
		return "redirect:/user/toIndexView";
	}

	/**
	 * @Description:TODO 注销
	 * @author: shuaibizhe
	 * @date: 2018年11月22日 下午8:49:42
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "logout")
	public String logout(HttpServletRequest request) {
		request.getSession().removeAttribute("loginUser");
		request.getSession().removeAttribute("filename");
		return "redirect:/user/toIndexView";
	}

	/**
	 * @Description:TODO 跳转到首页 查询热门推荐歌单
	 * @author: shuaibizhe
	 * @date: 2018年11月23日 下午4:37:21
	 * @param mv
	 * @return
	 */
	@RequestMapping(value = "toIndexView")
	public ModelAndView toIndexView(ModelAndView mv) {
		List<SongListVos> songListVos = null;
		try {
			songListVos = songlistService.toIndexView();
		} catch (Exception e) {
			e.printStackTrace();
		}
		mv.addObject("songListVos", songListVos);
		mv.setViewName("index");
		return mv;
	}

	/**
	 * @Description:TODO 验证码
	 * @author: shuaibizhe
	 * @date: 2018年11月25日 下午8:50:43
	 * @return
	 */
	@RequestMapping(value = "verify")
	@ResponseBody
	public String verify() {
		JSONObject json = new JSONObject();
		Random ra = new Random();
		String arr = "";
		int a = 0;
		for (int i = 0; i < 4; i++) {
			a = ra.nextInt(9);
			arr = arr + a;
		}
		json.put("msg", arr);
		return json.toString();
	}

	/**
	 * @Description:TODO 跳转到歌手页面
	 * @author: shuaibizhe
	 * @date: 2018年11月26日 下午2:27:56
	 * @return
	 */
	@RequestMapping(value = "toMusicPeople")
	public String toMusicPeople() {
		return "singer";
	}

	/**
	 * @Description:TODO 查找歌手
	 * @author: shuaibizhe
	 * @date: 2018年11月26日 下午3:44:27
	 * @param mv
	 * @param realName
	 * @return
	 */
	@RequestMapping(value = "selectSinger")
	public ModelAndView selectSinger(ModelAndView mv, String realName) {
		List<User> list = null;
		List<Song> singer = null;
		try {
			list = userService.selectSinger(realName);
			singer = songService.selectSinger(realName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (list.size() == 0 && singer.size() != 0) {// 未录入 但是有这个歌手 可以注册
			mv.addObject("singer", singer);
			mv.addObject("type", 1);
			mv.setViewName("singer");
		} else if (list.size() != 0 && singer.size() != 0) {// 已有歌手 不能录入
			mv.addObject("list", list);
			mv.addObject("type", 0);
			mv.setViewName("singer");
		} else if (list.size() != 0 && singer.size() == 0) {// 已经注册 不能录入
			mv.addObject("list", list);
			mv.addObject("type", 0);
			mv.setViewName("singer");
		} else {// 没有歌手也没有注册过 完全可以录入
			mv.addObject("type", 3);
			mv.setViewName("singer");

		}
		return mv;
	}

	/**
	 * @Description:TODO 跳转到条款页面
	 * @author: shuaibizhe
	 * @date: 2018年11月26日 下午3:45:20
	 * @return
	 */
	@RequestMapping(value = "toCheckSinger")
	public String toCheckSinger() {
		return "singer1";
	}

	/**
	 * @Description:TODO 入驻歌手 查看是否登陆
	 * @author: shuaibizhe
	 * @date: 2018年11月26日 下午5:07:14
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "checkLogin")
	@ResponseBody
	public String checkLogin(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		User user = (User) request.getSession().getAttribute("loginUser");
		if (user == null) {
			json.put("msg", "请先登录");
		} else {
			json.put("msg", 1);
		}
		return json.toString();
	}

	/**     
	 * @Description:TODO 上传头像
	 * @author: shuaibizhe
	 * @date:   2018年11月27日 上午9:59:48    
	 * @param file
	 * @param request
	 * @param realName
	 * @return      
	 */  
	@RequestMapping(value = "fileUpload", method = RequestMethod.POST)
	public String fileUpload(@RequestParam("filename") MultipartFile file, HttpServletRequest request,String realName) {
	try {
		// 获取上传文件的原始名称
		String org_filename = file.getOriginalFilename();
		// 设置上传文件的保存目录
		// String dirPath = "D:/upload/";
		// request.getServletContext().getRealPath("/upload/");
		System.err.println(path);
		File filePath = new File(path);
		// 如果保存文件的地址不存在，就先创建目录
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		// 使用UUID进行重命名
		String new_filename = UUID.randomUUID() + ".jpg";
		System.err.println(new_filename);
		// 使用MultipartFile 接口的方法 完成上传到指定位置
		file.transferTo(new File(path + "/" + new_filename));
		
		String pathName = path+new_filename;
		
		User user = (User) request.getSession().getAttribute("loginUser");
		user.setImapath(new_filename);
		user.setRealName(realName);
		user.setSinger(2);
		request.getSession().setAttribute("realName", realName);
		userService.updateRealName(user);
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	return "redirect:/user/toAbout";
}
	
	
	/**     
	 * @Description:TODO 上传歌曲
	 * @author: shuaibizhe
	 * @date:   2018年11月27日 上午9:59:56    
	 * @param file
	 * @param request
	 * @param realName
	 * @return      
	 */  
	@RequestMapping(value = "songUpload", method = RequestMethod.POST)
	public String songUpload(@RequestParam("filename") MultipartFile file, HttpServletRequest request,String songName,int type) {
	try {
		// 获取上传文件的原始名称
		String org_filename = file.getOriginalFilename();
		// 设置上传文件的保存目录
		// String dirPath = "D:/upload/";
		// request.getServletContext().getRealPath("/upload/");
		System.err.println(path);
		File filePath = new File(path);
		// 如果保存文件的地址不存在，就先创建目录
		if (!filePath.exists()) {
			filePath.mkdirs();
		}
		// 使用UUID进行重命名
		String new_filename = UUID.randomUUID() + ".mp3";
		System.err.println(new_filename);
		// 使用MultipartFile 接口的方法 完成上传到指定位置
		file.transferTo(new File(path + "/" + new_filename));
		
		String pathName = path+new_filename;
		
		User user = (User) request.getSession().getAttribute("loginUser");
		User user2 = userService.selectUserById(user);
		Song song = new Song();
		song.setSinger(user2.getRealName());
		song.setSongName(songName);
		song.setVipstate(0);
		song.setTypeId(type);
		song.setState(0);
		song.setSrc(pathName);
		song.setSongCounts(0);
		song.setTime("3:27");
		songService.insertSong(song);
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	return "redirect:/user/toAbout";
}
	
	/**
	 * @Description:TODO 跳转到个人主页
	 * @author: xulisa
	 * @date:   2018年11月26日 下午2:28:54    
	 * @return
	 */
	@RequestMapping(value="toAbout")
	public ModelAndView toAbout(HttpServletRequest request,ModelAndView mv){
		List<SongListVos> list = null;
		List<Song> songs = null;
		User user = (User) request.getSession().getAttribute("loginUser");
		User user2 = userService.selectUserById(user);
		int userId = user.getUserId();
		try {
			songs = songService.selectHistory(userId);
			list = songlistService.selectList(userId);
		} catch (Exception e) {
		}
		mv.addObject("list", list);
		mv.addObject("songs",songs);
		mv.addObject("li",user.getRealName());
		if (user2.getSinger()==1) {
			mv.addObject("singer","歌手");
			mv.addObject("type",1);
		}else {
			mv.addObject("singer","普通用户");
			mv.addObject("type",0);
		}
		mv.setViewName("about");
		return mv;
	}
	
	/**
	 * @Description:TODO修改资料
	 * @author: xulisa
	 * @date:   2018年11月26日 下午4:44:10    
	 * @return
	 */
	@RequestMapping(value="update")
	public String update(HttpServletRequest request,User user){
		User user2 = (User) request.getSession().getAttribute("loginUser");
		user.setUserId(user2.getUserId());
		try {
			userService.update(user);
			request.getSession().removeAttribute("loginUser");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "index";
	}
	
	/**     
	 * @Description:TODO 查看头像
	 * @author: shuaibizhe
	 * @date:   2018年11月27日 上午11:23:14    
	 * @param request
	 * @param response
	 * @throws Exception      
	 */  
	@RequestMapping(value = "show")
	public void showImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text/html; charset=UTF-8");
		response.setContentType("image/jpeg");
		
		User user = (User) request.getSession().getAttribute("loginUser");
		User user2 = userService.selectPath(user.getUserId());
		
		String fname = user2.getImapath();
		String newpath = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
		String absolutePath = path + newpath;//名字+路径
		FileInputStream fis = new FileInputStream(absolutePath);//里面有path
		OutputStream os = response.getOutputStream();
		try {
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}
	}
	
	/**     
	 * @Description:TODO 搜索歌手查看头像(这是通过a标签直接传值)
	 * @author: shuaibizhe
	 * @date:   2018年11月27日 下午2:52:51    
	 * @param request
	 * @param response
	 * @param userId
	 * @throws Exception      
	 */  
	@RequestMapping(value = "show1")
	public void showImage1(HttpServletRequest request, HttpServletResponse response,int userId) throws Exception {
		response.setContentType("text/html; charset=UTF-8");
		response.setContentType("image/jpeg");
		
		User user2 = userService.selectPath(userId);
		
		String fname = user2.getImapath();
		String newpath = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
		String absolutePath = path + newpath;//名字+路径
		FileInputStream fis = new FileInputStream(absolutePath);//里面有path
		OutputStream os = response.getOutputStream();
		try {
			int count = 0;
			byte[] buffer = new byte[1024 * 1024];
			while ((count = fis.read(buffer)) != -1)
				os.write(buffer, 0, count);
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (os != null)
				os.close();
			if (fis != null)
				fis.close();
		}
	}
}
